"""
Case Type   : toast表
Case Name   : 修改存储策略为plan/main，不会生成toast表
Create At   : 2024/08/07
Owner       : songjing20
Description :
    1.建表，查询字段信息
    2.修改存储策略为plain(避免压缩和行外存储),插入数据,查看是否有toast表生成
    3.修改存储策略为main(避免压缩和行外存储),插入数据,查看是否有toast表生成
    4.清理环境
Expect      :
    1.成功，id存储策略plain，info存储策略为extended
    2.成功,0
    3.成功,0
    4.成功
History     :
"""

import os
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class DmlTaost(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_toast_0005'
        self.col_storage = {'plain': 2, 'main': 3}

    def test_toast_table(self):
        text = '-----step1:建表，查询字段信息;' \
               'expect:成功，id存储策略plain，info存储策略为extended-----'
        self.log.info(text)
        res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;"
            f"create table {self.tb_name}("
            f"id serial primary key, info text not null"
            f") with(toast.autovacuum_enabled = false); \\d+ {self.tb_name}")
        self.log.info(res)
        self.assertEqual(res.count(self.constant.CREATE_TABLE_SUCCESS), 3,
                         f'建表失败:{text}')
        self.assertIn(f"id     | integer | not null default "
                      f"nextval('{self.tb_name}_id_seq'::regclass) | plain",
                      res, f'执行失败:{text}')
        self.assertIn(f"info   | text    | not null               "
                      f"                                   | extended",
                      res, f'执行失败:{text}')

        for storage, n in self.col_storage.items():
            text = f'-----step{n}:修改存储策略为{storage}，插入数据;expect:成功-----'
            self.log.info(text)
            res = self.pri_sh.execut_db_sql(
                f"alter table {self.tb_name} alter info set storage {storage};"
                f"insert into {self.tb_name}(info) "
                f"values(repeat('ab',1000));"
                f"select reltoastrelid from pg_class "
                f"where relname='{self.tb_name}';")
            self.log.info(res)
            self.assertIn(self.constant.ALTER_TABLE_MSG, res, f'执行失败:{text}')
            self.assertIn(self.constant.INSERT_SUCCESS_MSG, res, f'执行失败:{text}')
            self.assertIn('1 row', res, f'执行失败:{text}')

    def tearDown(self):
        text = '-----step4:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'删表失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
